﻿using System;
using System.Net.Http;
using Newtonsoft.Json;
using System.Threading.Tasks;
using System.Net;
using System.Diagnostics;

namespace nhCore.Http
{
    public delegate void OnOneRealTimeData<T>(T httpResult);

    /// <summary>
    /// http命令
    /// </summary>
    public class HttpHelper
    {
        /// <summary>
        /// 云平台读取数据
        /// </summary>
        /// <typeparam name="T">返回的数据类型</typeparam>
        /// <param name="cmd">发送请求命令</param>
        /// <param name="callback">回调函数</param>
        public static void GetDataAsync<T>(string cmd, OnOneRealTimeData<T> callback)
        {
            _ = Task.Run(async () =>
            {
                //使用GZip自动解压缩
                HttpClient httpClient = new HttpClient(new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip });
                HttpClient cnt = httpClient;
                HttpResponseMessage rst = await cnt.GetAsync(cmd);
                if (rst.StatusCode == HttpStatusCode.OK)
                {
                    string json = await rst.Content.ReadAsStringAsync();
                    T result = JsonConvert.DeserializeObject<T>(json);
                    Debug.WriteLine($"接收到云平台数据 State:{(result as ResultBase).State}{(result as ResultBase).Message}");
                    callback(result);
                }
            }).ContinueWith(t =>
            {
                if (t.IsFaulted && t.Exception != null)
                {
                    Debug.WriteLine(GetMessage(t.Exception));
                }
            });
        }

        private static string GetMessage(Exception exception)
        {
            var msg = string.Empty;
            if (exception != null)
            {
                msg = $"{exception.Message}\n{GetMessage(exception.InnerException)}";
            }
            return msg;
        }
    }
}
